package com.kaiwukj.android.ufamily.mvp.ui.page.order.mine;

import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.alipay.sdk.app.PayTask;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.kaiwukj.android.mcas.di.component.AppComponent;
import com.kaiwukj.android.ufamily.R;
import com.kaiwukj.android.ufamily.app.base.review.BaseMvpFragment;
import com.kaiwukj.android.ufamily.app.constant.ARouterUrlKt;
import com.kaiwukj.android.ufamily.app.constant.Constant;
import com.kaiwukj.android.ufamily.di.component.DaggerOrderComponent;
import com.kaiwukj.android.ufamily.di.module.OrderModule;
import com.kaiwukj.android.ufamily.mvp.http.entity.event.OrderEvent;
import com.kaiwukj.android.ufamily.mvp.http.entity.event.PayEvent;
import com.kaiwukj.android.ufamily.mvp.http.entity.event.PayInfo;
import com.kaiwukj.android.ufamily.mvp.http.entity.event.PayResult;
import com.kaiwukj.android.ufamily.mvp.http.entity.params.OrderPayParams;
import com.kaiwukj.android.ufamily.mvp.http.entity.result.HouseKeeperResult;
import com.kaiwukj.android.ufamily.mvp.http.entity.result.OrderDetailResult;
import com.kaiwukj.android.ufamily.mvp.http.entity.result.OrderResult;
import com.kaiwukj.android.ufamily.mvp.http.entity.result.ServiceResult;
import com.kaiwukj.android.ufamily.mvp.http.entity.resultbak.AlipayResult;
import com.kaiwukj.android.ufamily.mvp.ui.page.order.OrderContract;
import com.kaiwukj.android.ufamily.mvp.ui.page.order.OrderPresenter;
import com.kaiwukj.android.ufamily.mvp.ui.page.service.order.OrderResultActivity;
import com.qmuiteam.qmui.widget.dialog.QMUIBottomSheet;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;
import java.util.Map;

import butterknife.BindView;
import io.reactivex.Observable;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

public class MyOrderFragment extends BaseMvpFragment<OrderPresenter> implements OrderContract.View {

    private static final int REQUEST_EVALUATE = 101;

    @BindView(R.id.refresh_layout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.rv_list)
    RecyclerView rvList;


    private MyOrderAdapter mOrderAdapter;

    private int status = -1;
    private int page = 1;
    private int pageSize = 12;
    private boolean isLoadingMore = false;

    private int payWay;
    private int payPos = -1;


    public static MyOrderFragment newInstance(int status) {
        MyOrderFragment fragment = new MyOrderFragment();
        fragment.status = status;
        return fragment;
    }

    @Override
    public void setupFragmentComponent(@NonNull AppComponent appComponent) {
        super.setupFragmentComponent(appComponent);
        DaggerOrderComponent.builder()
                .appComponent(appComponent)
                .orderModule(new OrderModule(this))
                .build().inject(this);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.widget_list_normal;
    }

    @Override
    protected void initView() {
        refreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                isLoadingMore = true;
                ++page;
                loadData();
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                page = 1;
                loadData();
            }
        });
        rvList.setPadding(0, SizeUtils.dp2px(10), 0, 0);
        rvList.setLayoutManager(new LinearLayoutManager(getContext()));
        //rvList.addItemDecoration(new SpaceItemDecoration(5));
        mOrderAdapter = new MyOrderAdapter();
        rvList.setAdapter(mOrderAdapter);
        mOrderAdapter.setEmptyView(R.layout.widget_empty_common);

        mOrderAdapter.setOnItemClickListener((adapter, view, position) -> {
            ARouter.getInstance().build(ARouterUrlKt.OrderDetailUrl)
                    .withInt("orderId", (int) adapter.getItemId(position))
                    .navigation();
        });

        mOrderAdapter.setOnItemOrderEvent(new MyOrderAdapter.OnItemOrderEvent() {
            @Override
            public void onOrderDetail(int position) {
                ARouter.getInstance().build(ARouterUrlKt.OrderDetailUrl)
                        .withInt("orderId", (int) mOrderAdapter.getItemId(position))
                        .navigation();
            }

            @Override
            public void onOrderCancel(int position) {
                showMessageOKCancel(getActivity(), "是否确定取消退款", v ->
                        mPresenter.cancelOrder((int) mOrderAdapter.getItemId(position)));
            }

            @Override
            public void onOrderPay(int position) {
                new QMUIBottomSheet.BottomListSheetBuilder(getContext())
                        .addItem(R.mipmap.ic_pay_wechat, "微信", "微信")
                        .addItem(R.mipmap.ic_pay_alipay, "支付宝", "支付宝")
                        .setGravityCenter(true)
                        .setOnSheetItemClickListener((dialog, itemView, position1, tag) -> {
                            dialog.dismiss();
                            payPos = position;
                            OrderPayParams payParams = new OrderPayParams();
                            payParams.setOrderId(mOrderAdapter.getItem(position).getId());
                            payParams.setOrderNum(mOrderAdapter.getItem(position).getOrderNum());
                            payWay = position1 == 0 ? 2 : 1;
                            payParams.setPayType(payWay);
                            mPresenter.payOrder(payParams);
                            showLoading("正在请求...");
                        })
                        .build().show();

            }

            @Override
            public void onOrderAgain(int position) {
                ServiceResult.ServiceInfo params = new ServiceResult.ServiceInfo();
                params.setId(mOrderAdapter.getItem(position).getServiceParameterId());
                params.setParameterName(mOrderAdapter.getItem(position).getServiceParameterName());
                params.setCharges(mOrderAdapter.getItem(position).getUnitPrice());
                ARouter.getInstance().build(ARouterUrlKt.OrderCreateUrl)
                        .withSerializable("params", params)
                        .navigation();
            }

            @Override
            public void onOrderEvaluate(int position) {
                OrderResult result = mOrderAdapter.getItem(position);
                ARouter.getInstance().build(ARouterUrlKt.OrderEvaluateEditUrl)
                        .withInt("orderId", result.getId())
                        .withString("avatarUrl", result.getThumbnail())
                        .withString("serviceName", result.getServiceParameterName())
                        .withString("servicePrice", result.getOrderPriceStr())
                        .navigation(getActivity(), REQUEST_EVALUATE);
            }

            @Override
            public void onOrderDelete(int position) {
                showMessageOKCancel(getActivity(), "是否确定删除订单", v ->
                        mPresenter.deleteOrder((int) mOrderAdapter.getItemId(position)));
            }
        });
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        showLoading();
        loadData();
    }


    private void loadData() {
        mPresenter.fetchList(status, page, pageSize);
    }

    @Override
    public void onFetchOrder(List<OrderResult> results) {
        hideLoading();
        if (isLoadingMore) {
            isLoadingMore = false;
            mOrderAdapter.addData(results);
            if (results.size() < pageSize) {
                refreshLayout.finishLoadMoreWithNoMoreData();
            } else {
                refreshLayout.finishLoadMore();
            }
        } else {
            mOrderAdapter.setList(results);
            refreshLayout.finishRefresh(true);
        }
    }

    @Override
    public void onGetOrder(OrderDetailResult result) {

    }

    @Override
    public void onOrderPayResult(Map<String, Object> result) {
        hideLoading();
        if (payWay == 1) {
            payByAlipay(GsonUtils.toJson(result));
        } else {
            payByWechat(GsonUtils.toJson(result));
        }
    }

    @Override
    public void onGetHouseKeeper(HouseKeeperResult result) {

    }

    private void payByWechat(String sign) {
        PayInfo payInfo = GsonUtils.fromJson(sign, PayInfo.class);
        final IWXAPI msgApi = WXAPIFactory.createWXAPI(getContext(), null);
        msgApi.registerApp(Constant.WX_APP_ID);
        if (!msgApi.isWXAppInstalled()) {
            showMessage(getString(R.string.please_install_wechat));
            return;
        }
        msgApi.sendReq(payInfo.getPayReq());
    }

    private void payByAlipay(String sign) {
        AlipayResult payObj = GsonUtils.fromJson(sign, AlipayResult.class);
        subscribe(Observable.create((ObservableOnSubscribe<PayResult>) emitter -> {
            PayTask payTask = new PayTask(getActivity());
            Map<String, String> map = payTask.payV2(payObj.getSign(), true);
            emitter.onNext(new PayResult(map));
        }).subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(payResult -> {
                    if ("9000".equals(payResult.getResultStatus())) {
                        //EventBus.getDefault().post(new PayEvent(true, 0, "支付成功"));
                        // showMessage("支付成功");
                        onPaySuccess();
                    } else if ("6001".equals(payResult.getResultStatus())) {
                        //cancelOrder(new PayFeeCancelRequest(result.getTradeNo()));
                        showMessage("支付取消");
                    } else {
                        //EventBus.getDefault().post(new PayEvent(false, 0, "支付失败"));
                        showMessage("支付失败:" + payResult.getResultStatus());
                    }
                }));
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onPayEvent(PayEvent payEvent) {
        if (payEvent.isSuccess()) {
            onPaySuccess();
        } else {
            showMessage(payEvent.getDesc());
        }
    }

    private void onPaySuccess() {

        if (payPos < 0) {
            showMessage("订单信息获取失败，请稍后刷新");
            return;
        }
        OrderResult result = mOrderAdapter.getItem(payPos);

        ARouter.getInstance().build(ARouterUrlKt.OrderResultUrl)
                .withInt("type", OrderResultActivity.ORDER_PAY)
                .withInt("orderId", result.getId())
                .withString("orderNo", result.getOrderNum())
                .withString("appointmentTime", result.getAppointmentTime())
                .navigation();
    }

    @Override
    public void onTaskErr(int taskId) {
        super.onTaskErr(taskId);
        hideLoading();
        refreshLayout.finishRefresh(false);
        refreshLayout.finishLoadMore(false);
    }

    @Override
    public void onTaskSuccess(int taskId) {
        super.onTaskSuccess(taskId);
        if (taskId > 0) {
            page = 1;
            loadData();
        }
    }

    public void onOrderEvent(OrderEvent event) {
        int orderId = event.getEventId();
        switch (event.getEventCode()) {
            case OrderEvent.DELETE:
                if (orderId > 0 && mOrderAdapter != null) {
                    mOrderAdapter.deleteOrder(orderId);
                } else {
                    page = 1;
                    loadData();
                }
                break;
            case OrderEvent.INVALID:
                if (orderId > 0 && mOrderAdapter != null) {
                    mOrderAdapter.invalidOrder(orderId);
                } else {
                    page = 1;
                    loadData();
                }
                break;
            default:
                page = 1;
                loadData();
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_EVALUATE) {
            if (resultCode == RESULT_OK) {
                page = 1;
                loadData();
            }
        }
    }
}
